﻿using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Kyoh.App.Crawler.Plugin;
using Kyoh.Lib.IO;
using Kyoh.Lib.Plugin;
using System.IO;
using System.Windows.Forms;

namespace Kyoh.App.Crawler.Contents
{
    /// <summary>パーサーの管理を行うクラス。</summary>
    class Parsers : PluginManager<IParser>
    {
        public Task<Loader> ParseAsync(string pageUri)
        {
            return Task<Loader>.Factory.StartNew(() =>
                Parse(pageUri));
        }

        public Loader Parse(string pageUri)
        {
            foreach (var parser in this)
            {
                try
                {
                    if (parser.Supports(pageUri))
                    {
                        var loader = parser.Parse(pageUri);
                        if (loader == null)
                        {
                            Trace.TraceError(Properties.Strings.ErrorEmptyLoader, string.Empty, pageUri);
                        }
                        else if (loader.ContentUri == null)
                        {
                            Trace.TraceError(Properties.Strings.ErrorEmptyLoader, loader.Title, pageUri);
                        }
                        else
                        {
                            return new Loader(loader);
                        }
                    }
                }
                catch (Exception exc)
                {
                    Trace.TraceWarning(Properties.Strings.WarningParseUri, parser.Name, pageUri);
                    Debug.WriteLine(exc);
                }
            }
            Trace.TraceWarning(Properties.Strings.WarningNotSupportedUri, Properties.Strings.Parser, string.Empty, pageUri);
            return null;
        }
    }
}